package com.sihai.ehr.service.impl;

import java.util.Calendar;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Service;

import com.sihai.core.DataAccessor;
import com.sihai.core.DynamicQuery;
import com.sihai.core.Limit;
import com.sihai.core.LimitedList;
import com.sihai.core.QueryCreator;
import com.sihai.core.Sorter;
import com.sihai.ehr.model.biz.ExamQualScore;
import com.sihai.ehr.model.biz.ExamQualScoreDetail;
import com.sihai.ehr.model.biz.ExamQualTargetAuditing;
import com.sihai.ehr.model.biz.TrainPlan;
import com.sihai.ehr.model.biz.TrainPlanAuditing;
import com.sihai.ehr.model.sys.AuditStatus;
import com.sihai.ehr.model.sys.ExamShowYearlyEnum;
import com.sihai.ehr.model.sys.ExaminePeriodEnum;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.repository.AuditingRepository;
import com.sihai.ehr.service.ExamQualScoreService;
import com.sihai.ehr.web.pojo.ExamQualScoreItemPojo;
import com.sihai.ehr.web.pojo.ExamQualScorePojo;

/**
 * 定性考核打分服务实现类
 * 
 * @author Henry
 * 
 */
@Service("examQualScoreService")
public class ExamQualScoreServiceImpl implements ExamQualScoreService {

	@Resource
	DataAccessor dataAccessor;
	
	@Resource
	private AuditingRepository auditingRepository;

	@Override
	public ExamQualScore getExamQualScore(Long id) {
		if (id == null || id < 0) {
			throw new RuntimeException("【传入参数非法】");
		}
		try {
			return dataAccessor.get(ExamQualScore.class, id);
		} catch (Exception e) {
			throw new RuntimeException("【异常原因：获取定性考核员工分数数据库发生异常】【异常说明：+"
					+ e.getMessage()
					+ "】【发生地点：ExamQualScoreServiceImpl.getExamQualScore;参数id="
					+ id + " 】");
		}
	}

	@Override
	public ExamQualScore getExamQualScore(final Long periodId, final Long workId) {
		if (periodId == null || periodId <= 0) {
			return null;
		}
		if (workId == null || workId <= 0) {
			throw new RuntimeException("【传入参数非法】");
		}
		try {
			return dataAccessor.findUnique(ExamQualScore.class,
					new QueryCreator() {
						@Override
						public Query createQuery(Session session) {
							String hql = "from ExamQualScore e where e.examPeriod.id=:periodId and e.employeeinfoWork.id=:workId";
							Query query = session.createQuery(hql);
							query.setParameter("periodId", periodId);
							query.setParameter("workId", workId);
							return query;
						}
					});
		} catch (Exception e) {
			throw new RuntimeException(
					"【异常原因：获取定性考核员工分数数据库发生异常】【异常说明：+"
							+ e.getMessage()
							+ "】【发生地点：ExamQualScoreServiceImpl.getExamQualScore;参数workId="
							+ workId + " 】");
		}
	}

	@Override
	public ExamQualScoreDetail getExamQualScoreDetail(Long id) {
		if (id == null || id < 0) {
			throw new RuntimeException("【传入参数非法】");
		}
		try {
			return dataAccessor.get(ExamQualScoreDetail.class, id);
		} catch (Exception e) {
			throw new RuntimeException(
					"【异常原因：获取定性考核员工分数明细数据库发生异常】【异常说明：+"
							+ e.getMessage()
							+ "】【发生地点：ExamQualScoreServiceImpl.getExamQualScoreDetail;参数id="
							+ id + " 】");
		}
	}

	@Override
	public ExamQualScoreDetail getExamQualScoreDetailByScItemId(
			final Long scoreId, final Long itemId) {
		if (scoreId == null || scoreId <= 0) {
			return null;
		}
		if (itemId == null || itemId <= 0) {
			throw new RuntimeException("【传入参数非法】");
		}
		try {
			return dataAccessor.findUnique(ExamQualScoreDetail.class,
					new QueryCreator() {
						@Override
						public Query createQuery(Session session) {
							String hql = "from ExamQualScoreDetail e where e.examScore.id=:scoreId and e.examQualItemSet.id=:itemId";
							Query query = session.createQuery(hql);
							query.setParameter("scoreId", scoreId);
							query.setParameter("itemId", itemId);
							return query;
						}
					});
		} catch (Exception e) {
			throw new RuntimeException(
					"【异常原因：获取定性考核员工分数数据库发生异常】【异常说明：+"
							+ e.getMessage()
							+ "】【发生地点：ExamQualScoreServiceImpl.getExamQualScoreDetailByScItemId;参数itemId="
							+ itemId + " 】");
		}
	}

	public LimitedList<ExamQualScorePojo> searchNotInputExamQualScores(
			final Long organizationId, final String dutyIds,
			final ExaminePeriodEnum periodType, final Long period,
			final int year, final int month, final int status, Limit limit,
			Sorter sorter) {
		try {
			/*
			 * Organization organization = null; boolean isReadTopOrg = false;
			 * if (organizationId > 0) { try { organization =
			 * dataAccessor.get(Organization.class, organizationId); if
			 * (organization.getTopOrganization() == null) { isReadTopOrg =
			 * true; } } catch (Exception e) { return null; } }
			 * 
			 * final boolean isReadTopOrganization = isReadTopOrg;
			 */
			String treepath = "";
			if (organizationId > 0) {
				try {
					treepath = dataAccessor.get(Organization.class,
							organizationId).getTreePath();
				} catch (Exception e) {
					return null;
				}
			}
			final String treePath = treepath;

			return dataAccessor.findByQuery(ExamQualScorePojo.class,
					new QueryCreator() {

						@Override
						public Query createQuery(Session session) {
							// Calendar mCalendar = Calendar.getInstance();
							// mCalendar.add(Calendar.MONTH, -1);
							DynamicQuery dynamicQuery = new DynamicQuery(
									"select new com.sihai.ehr.web.pojo.ExamQualScorePojo(w.id,w.baseId.name,w.organization.fullName,w.duty.dutyName,w.grade.gradeName,w.gradeLevel.gradeSort)"
											+ " from EmployeeinfoWork w where w.cancel <> 1");

							/*
							 * if (isReadTopOrganization) { dynamicQuery
							 * .appendIfNotNull(
							 * "and (w.organization.topOrganization.id=:organization_id or w.organization.id =:organization_id)"
							 * , "organization_id", organizationId); } else if
							 * (organizationId > 0) { dynamicQuery
							 * .appendIfNotNull(
							 * "and w.organization.id =:organization_id",
							 * "organization_id", organizationId); }
							 */
							// modify by henry #start ---->for the read all
							// child
							dynamicQuery
									.append("and w.organization.treePath like '"
											+ treePath + "%'");
							// modify by henry #end

							if (dutyIds != null && !dutyIds.isEmpty()) {
								dynamicQuery.append("and w.duty.id in("
										+ dutyIds + ")");
							}
							dynamicQuery
									.append("and not exists(select 1 from ExamQualScore e where e.employeeinfoWork.id=w.id "
											+ "and e.examPeriod.examYear="
											+ year
											+ " and e.examPeriod.examMonthly="
											+ month + ")");

							return dynamicQuery.build(session);
						}
					}, limit, sorter);
		} catch (Exception e) {
			throw new RuntimeException(
					"【异常原因：获取定性考核打分对象集合时数据库发生异常】【异常说明：+"
							+ e.getMessage()
							+ "】【发生地点：ExamQualScoreServiceImpl.searchExamQualScores;参数organizationId="
							+ organizationId + ",periodType=" + periodType
							+ "】");
		}
	}

	@Override
	public LimitedList<ExamQualScorePojo> searchExamQualScores(
			final Long organizationId, final String dutyIds,
			final ExaminePeriodEnum periodType, final Long period,
			final int year, final int month, final int status, Limit limit,
			Sorter sorter) {
		try {
			/*
			 * Organization organization = null; boolean isReadTopOrg = false;
			 * if (organizationId > 0) { try { organization =
			 * dataAccessor.get(Organization.class, organizationId); if
			 * (organization.getTopOrganization() == null) { isReadTopOrg =
			 * true; } } catch (Exception e) { return null; } }
			 * 
			 * final boolean isReadTopOrganization = isReadTopOrg;
			 */
			String treepath = "";
			if (organizationId > 0) {
				try {
					treepath = dataAccessor.get(Organization.class,
							organizationId).getTreePath();
				} catch (Exception e) {
					return null;
				}
			}
			final String treePath = treepath;
			return dataAccessor.findByQuery(ExamQualScorePojo.class,
					new QueryCreator() {

						@Override
						public Query createQuery(Session session) {
							// Calendar mCalendar = Calendar.getInstance();
							// mCalendar.add(Calendar.MONTH, -1);
							DynamicQuery dynamicQuery = new DynamicQuery(
									"select new com.sihai.ehr.web.pojo.ExamQualScorePojo(e.id,w.id,w.baseId.name,w.organization.fullName,w.duty.dutyName,w.grade.gradeName,w.gradeLevel.gradeSort,e.rawScore,e.adjustScore)"
											+ " from ExamQualScore e right join e.employeeinfoWork w where w.cancel <> 1");

							/*
							 * if (isReadTopOrganization) { dynamicQuery
							 * .appendIfNotNull(
							 * "and (w.organization.topOrganization.id=:organization_id or w.organization.id =:organization_id)"
							 * , "organization_id", organizationId); } else if
							 * (organizationId > 0) { dynamicQuery
							 * .appendIfNotNull(
							 * "and w.organization.id =:organization_id",
							 * "organization_id", organizationId); }
							 */
							// modify by henry #start ---->for the read all
							// child
							dynamicQuery
									.append("and w.organization.treePath like '"
											+ treePath + "%'");
							// modify by henry #end
							if (dutyIds != null && !dutyIds.isEmpty()) {
								dynamicQuery.append("and w.duty.id in("
										+ dutyIds + ")");
							}

							if (period > 0) {
								if (status > -1) {
									// 表示打过分的
									dynamicQuery
											.appendIfNotNull(
													"and e.examPeriod.periodType =:periodType",
													"periodType", periodType);
									dynamicQuery.append(
											"and e.examPeriod.id =:period_id",
											"period_id", period);
								} else {
									dynamicQuery
											.append("and not exists(select p.id from ExamPeriod p where p.id=e.examPeriod.id and p.id=:period_id)",
													"period_id", period);
								}

							} else {
								// 当前周期未打分过
								if (status > -1) {
									// 表示打过分的
									dynamicQuery
											.appendIfNotNull(
													"and e.examPeriod.periodType =:periodType",
													"periodType", periodType);
									dynamicQuery
											.append("and e.examPeriod.examYear =:exam_year",
													"exam_year", year);
									dynamicQuery
											.append("and e.examPeriod.examMonthly =:exam_monthly",
													"exam_monthly", month);

								} else {
									dynamicQuery
											.append("and not exists(select 1 from ExamPeriod p where p.id=e.examPeriod.id "
													+ "and p.examYear="
													+ year
													+ " and p.examMonthly="
													+ month + ")");
								}
							}

							if (status > 0) {
								dynamicQuery.append("and e.status =:status",
										"status", status);
							}
							return dynamicQuery.build(session);
						}
					}, limit, sorter);
		} catch (Exception e) {
			throw new RuntimeException(
					"【异常原因：获取定性考核打分对象集合时数据库发生异常】【异常说明：+"
							+ e.getMessage()
							+ "】【发生地点：ExamQualScoreServiceImpl.searchExamQualScores;参数organizationId="
							+ organizationId + ",periodType=" + periodType
							+ "】");
		}
	}
	
	@Override
	public LimitedList<ExamQualScorePojo> searchRequestAuditExamQualScores(
			final Long organizationId, final String dutyIds,
			final ExaminePeriodEnum periodType, final Long period,
			final int year, final int month, final int status, Limit limit,
			Sorter sorter) {
		try {
			String treepath = "";
			if (organizationId > 0) {
				try {
					treepath = dataAccessor.get(Organization.class,
							organizationId).getTreePath();
				} catch (Exception e) {
					return null;
				}
			}
			final String treePath = treepath;
			return dataAccessor.findByQuery(ExamQualScorePojo.class,
					new QueryCreator() {

						@Override
						public Query createQuery(Session session) {
							// Calendar mCalendar = Calendar.getInstance();
							// mCalendar.add(Calendar.MONTH, -1);
							DynamicQuery dynamicQuery = new DynamicQuery(
									"select new com.sihai.ehr.web.pojo.ExamQualScorePojo(e.id,w.id,w.baseId.name,w.organization.fullName,w.duty.dutyName,w.grade.gradeName,w.gradeLevel.gradeSort,e.rawScore,e.adjustScore)"
											+ " from ExamQualScore e right join e.employeeinfoWork w where w.cancel <> 1");
							// modify by henry #start ---->for the read all
							// child
							dynamicQuery
									.append("and w.organization.treePath like '"
											+ treePath + "%'");
							// modify by henry #end
							if (dutyIds != null && !dutyIds.isEmpty()) {
								dynamicQuery.append("and w.duty.id in("
										+ dutyIds + ")");
							}

							if (period > 0) {
								if (status > -1) {
									// 表示打过分的
									dynamicQuery
											.appendIfNotNull(
													"and e.examPeriod.periodType =:periodType",
													"periodType", periodType);
									dynamicQuery.append(
											"and e.examPeriod.id =:period_id",
											"period_id", period);
								} else {
									dynamicQuery
											.append("and not exists(select p.id from ExamPeriod p where p.id=e.examPeriod.id and p.id=:period_id)",
													"period_id", period);
								}

							} else {
								// 当前周期未打分过
								if (status > -1) {
									// 表示打过分的
									dynamicQuery
											.appendIfNotNull(
													"and e.examPeriod.periodType =:periodType",
													"periodType", periodType);
									dynamicQuery
											.append("and e.examPeriod.examYear =:exam_year",
													"exam_year", year);
									dynamicQuery
											.append("and e.examPeriod.examMonthly =:exam_monthly",
													"exam_monthly", month);

								} else {
									dynamicQuery
											.append("and not exists(select 1 from ExamPeriod p where p.id=e.examPeriod.id "
													+ "and p.examYear="
													+ year
													+ " and p.examMonthly="
													+ month + ")");
								}
							}

							if (status > 0) {
								dynamicQuery.append("and e.status =:status",
										"status", status);
							}
							dynamicQuery.append(" and e.adjustScore is not null");
							dynamicQuery.append(" and e.currentAuditStatus =:auditStatus","auditStatus",AuditStatus.within_audit);
							return dynamicQuery.build(session);
						}
					}, limit, sorter);
		} catch (Exception e) {
			throw new RuntimeException(
					"【异常原因：获取定性考核打分对象集合时数据库发生异常】【异常说明：+"
							+ e.getMessage()
							+ "】【发生地点：ExamQualScoreServiceImpl.searchRequestAuditExamQualScores;参数organizationId="
							+ organizationId + ",periodType=" + periodType
							+ "】");
		}
	}
	
	@Override
	public LimitedList<ExamQualScorePojo> searchHasAuditExamQualScores(
			final Long organizationId, final String dutyIds,
			final ExaminePeriodEnum periodType, final Long period,
			final int year, final int month, final int status, Limit limit,
			Sorter sorter) {
		try {
			String treepath = "";
			if (organizationId > 0) {
				try {
					treepath = dataAccessor.get(Organization.class,
							organizationId).getTreePath();
				} catch (Exception e) {
					return null;
				}
			}
			final String treePath = treepath;
			return dataAccessor.findByQuery(ExamQualScorePojo.class,
					new QueryCreator() {

						@Override
						public Query createQuery(Session session) {
							// Calendar mCalendar = Calendar.getInstance();
							// mCalendar.add(Calendar.MONTH, -1);
							DynamicQuery dynamicQuery = new DynamicQuery(
									"select new com.sihai.ehr.web.pojo.ExamQualScorePojo(e.id,w.id,w.baseId.name,w.organization.fullName,w.duty.dutyName,w.grade.gradeName,w.gradeLevel.gradeSort,e.rawScore,e.adjustScore)"
											+ " from ExamQualScore e right join e.employeeinfoWork w where w.cancel <> 1");
							// modify by henry #start ---->for the read all
							// child
							dynamicQuery
									.append("and w.organization.treePath like '"
											+ treePath + "%'");
							// modify by henry #end
							if (dutyIds != null && !dutyIds.isEmpty()) {
								dynamicQuery.append("and w.duty.id in("
										+ dutyIds + ")");
							}

							if (period > 0) {
								if (status > -1) {
									// 表示打过分的
									dynamicQuery
											.appendIfNotNull(
													"and e.examPeriod.periodType =:periodType",
													"periodType", periodType);
									dynamicQuery.append(
											"and e.examPeriod.id =:period_id",
											"period_id", period);
								} else {
									dynamicQuery
											.append("and not exists(select p.id from ExamPeriod p where p.id=e.examPeriod.id and p.id=:period_id)",
													"period_id", period);
								}

							} else {
								// 当前周期未打分过
								if (status > -1) {
									// 表示打过分的
									dynamicQuery
											.appendIfNotNull(
													"and e.examPeriod.periodType =:periodType",
													"periodType", periodType);
									dynamicQuery
											.append("and e.examPeriod.examYear =:exam_year",
													"exam_year", year);
									dynamicQuery
											.append("and e.examPeriod.examMonthly =:exam_monthly",
													"exam_monthly", month);

								} else {
									dynamicQuery
											.append("and not exists(select 1 from ExamPeriod p where p.id=e.examPeriod.id "
													+ "and p.examYear="
													+ year
													+ " and p.examMonthly="
													+ month + ")");
								}
							}

							if (status > 0) {
								dynamicQuery.append("and e.status =:status",
										"status", status);
							}
							dynamicQuery.append(" and e.adjustScore is not null");
							dynamicQuery.append(" and e.currentAuditStatus <>:auditStatus","auditStatus",AuditStatus.within_audit);
							return dynamicQuery.build(session);
						}
					}, limit, sorter);
		} catch (Exception e) {
			throw new RuntimeException(
					"【异常原因：获取定性考核打分对象集合时数据库发生异常】【异常说明：+"
							+ e.getMessage()
							+ "】【发生地点：ExamQualScoreServiceImpl.searchRequestAuditExamQualScores;参数organizationId="
							+ organizationId + ",periodType=" + periodType
							+ "】");
		}
	}
	
	@Override
	public Long searchExamDistQualScoreCountByStatus(
			final Long organizationId, final String dutyIds,
			final ExaminePeriodEnum periodType, final Long period,
			final int status) {
		try {
			String treepath = "";
			if (organizationId > 0) {
				try {
					treepath = dataAccessor.get(Organization.class,
							organizationId).getTreePath();
				} catch (Exception e) {
					return null;
				}
			}
			final String treePath = treepath;
			return dataAccessor.findUnique(Long.class, new QueryCreator() {

						@Override
						public Query createQuery(Session session) {
							Calendar mCalendar = Calendar.getInstance();
							mCalendar.add(Calendar.MONTH, -1);
							DynamicQuery dynamicQuery = new DynamicQuery(
									"select count(e.id) from ExamQualScore e right join e.employeeinfoWork w where w.cancel <> 1");

							// modify by henry #start ---->for the read all
							// child
							dynamicQuery
									.append("and w.organization.treePath like '"
											+ treePath + "%'");
							// modify by henry #end
							if (dutyIds != null && !dutyIds.isEmpty()) {
								dynamicQuery.append("and w.duty.id in("
										+ dutyIds + ")");
							}
							// 表示打过分的
							dynamicQuery.appendIfNotNull(
									"and e.examPeriod.periodType =:periodType",
									"periodType", periodType);
							dynamicQuery.append(
									"and e.examPeriod.id =:period_id",
									"period_id", period);
							if (status > 0) {
								dynamicQuery.append("and e.status =:status",
										"status", status);
							}
							return dynamicQuery.build(session);
						}
					});
		} catch (Exception e) {
			throw new RuntimeException(
					"【异常原因：获取定性考核打分对象集合时数据库发生异常】【异常说明：+"
							+ e.getMessage()
							+ "】【发生地点：ExamQualScoreServiceImpl.searchExamDistQualScoresByStatus;参数organizationId="
							+ organizationId + ",periodType=" + periodType
							+ "】");
		}
	}

	@Override
	public LimitedList<ExamQualScorePojo> searchExamDistQualScores(
			final Long organizationId, final String dutyIds,
			final ExaminePeriodEnum periodType, final Long period,
			final int status, final Float scoreStart, final Float scoreEnd,
			Limit limit, Sorter sorter) {
		try {
			/*
			 * Organization organization = null; boolean isReadTopOrg = false;
			 * if (organizationId > 0) { try { organization =
			 * dataAccessor.get(Organization.class, organizationId); if
			 * (organization.getTopOrganization() == null) { isReadTopOrg =
			 * true; } } catch (Exception e) { return null; } }
			 * 
			 * final boolean isReadTopOrganization = isReadTopOrg;
			 */
			String treepath = "";
			if (organizationId > 0) {
				try {
					treepath = dataAccessor.get(Organization.class,
							organizationId).getTreePath();
				} catch (Exception e) {
					return null;
				}
			}
			final String treePath = treepath;
			return dataAccessor.findByQuery(ExamQualScorePojo.class,
					new QueryCreator() {

						@Override
						public Query createQuery(Session session) {
							Calendar mCalendar = Calendar.getInstance();
							mCalendar.add(Calendar.MONTH, -1);
							DynamicQuery dynamicQuery = new DynamicQuery(
									"select new com.sihai.ehr.web.pojo.ExamQualScorePojo(e.id,w.id,w.baseId.name,w.organization.fullName,w.duty.dutyName,w.grade.gradeName,w.gradeLevel.gradeSort,e.rawScore,e.adjustScore)"
											+ " from ExamQualScore e right join e.employeeinfoWork w where w.cancel <> 1");

							/*
							 * if (isReadTopOrganization) { dynamicQuery
							 * .appendIfNotNull(
							 * "and (w.organization.topOrganization.id=:organization_id or w.organization.id =:organization_id)"
							 * , "organization_id", organizationId); } else if
							 * (organizationId > 0) { dynamicQuery
							 * .appendIfNotNull(
							 * "and w.organization.id =:organization_id",
							 * "organization_id", organizationId); }
							 */

							// modify by henry #start ---->for the read all
							// child
							dynamicQuery
									.append("and w.organization.treePath like '"
											+ treePath + "%'");
							// modify by henry #end
							if (dutyIds != null && !dutyIds.isEmpty()) {
								dynamicQuery.append("and w.duty.id in("
										+ dutyIds + ")");
							}
							// 表示打过分的
							dynamicQuery.appendIfNotNull(
									"and e.examPeriod.periodType =:periodType",
									"periodType", periodType);
							dynamicQuery.append(
									"and e.examPeriod.id =:period_id",
									"period_id", period);
							if (scoreStart >= 0 && scoreEnd <= 100) {
								/*dynamicQuery
								.append("and (e.rawScore between "
										+ scoreStart + " and "
										+ scoreEnd
										+ " or e.adjustScore between "
										+ scoreStart + " and "
										+ scoreEnd + ")");*/
								dynamicQuery.append("and e.rawScore between "
										+ scoreStart + " and " + scoreEnd);
							}
							if (status > 0) {
								dynamicQuery.append("and e.status =:status",
										"status", status);
							}
							return dynamicQuery.build(session);
						}
					}, limit, sorter);
		} catch (Exception e) {
			throw new RuntimeException(
					"【异常原因：获取定性考核打分对象集合时数据库发生异常】【异常说明：+"
							+ e.getMessage()
							+ "】【发生地点：ExamQualScoreServiceImpl.searchExamQualScores;参数organizationId="
							+ organizationId + ",periodType=" + periodType
							+ "】");
		}
	}

	@Override
	public LimitedList<ExamQualScore> searchEmployeeExamQualScores(
			final Long workId, final ExaminePeriodEnum periodEnum,
			final int year, Limit limit, Sorter sorter) {
		if (workId == null || workId <= 0) {
			throw new RuntimeException(
					"【examQualScore参数异常】【发生地点：ExamQualScoreServiceImpl.searchEmployeeExamQualScores】");
		}
		try {
			return dataAccessor.findByQuery(ExamQualScore.class,
					new QueryCreator() {
						@Override
						public Query createQuery(Session session) {
							// right join i.employeeinfoBase
							DynamicQuery dynamicQuery = new DynamicQuery(
									"from ExamQualScore e where 1<>2");// right
																		// join
																		// e.employeeinfoWork
																		// w
																		// where
																		// w.cancel
																		// <> 1
							dynamicQuery.append(
									" and e.employeeinfoWork.id = :work_id",
									"work_id", workId);
							dynamicQuery
									.append(" and e.examPeriod.periodType = :period_type",
											"period_type", periodEnum);
							if (year > 0) {
								dynamicQuery
										.append(" and e.examPeriod.examYear = :exam_year",
												"exam_year", year);
							}
							dynamicQuery
									.append(" order by e.examPeriod.examYear asc,e.examPeriod.examMonthly asc");
							return dynamicQuery.build(session);
						}
					}, limit, sorter);
		} catch (Exception e) {
			throw new RuntimeException(
					"【异常原因：获取定性考核打分对象集合时数据库发生异常】【异常说明：+"
							+ e.getMessage()
							+ "】【发生地点：ExamQualScoreServiceImpl.searchEmployeeExamQualScores;参数workId="
							+ workId + ",year:" + year + "】");
		}
	}

	@Override
	public LimitedList<ExamQualScoreItemPojo> searchExamQualScoreDetails(
			final Long examscoreId, final Long topOrgId, Limit limit,
			Sorter sorter) {
		try {
			return dataAccessor.findByQuery(ExamQualScoreItemPojo.class,
					new QueryCreator() {

						@Override
						public Query createQuery(Session session) {
							if (examscoreId <= 0) {
								DynamicQuery dynamicQuery = new DynamicQuery(
										"select new com.sihai.ehr.web.pojo.ExamQualScoreItemPojo(i.id,i.title,i.percentage,"
												+ "i.desc1,i.desc2,i.desc3,i.desc4,i.desc5,i.desc6,i.desc7,i.desc8,i.desc9,i.desc10)"
												+ " from ExamQualItemSet i where 1<>2");
								dynamicQuery
										.appendIfNotNull(
												"and i.organization.id =:organization_id",
												"organization_id", topOrgId);
								return dynamicQuery.build(session);
							} else {
								DynamicQuery dynamicQuery = new DynamicQuery(
										"select new com.sihai.ehr.web.pojo.ExamQualScoreItemPojo(e.id,i.id,i.title,i.percentage,"
												+ "i.desc1,i.desc2,i.desc3,i.desc4,i.desc5,i.desc6,i.desc7,i.desc8,i.desc9,i.desc10,"
												+ "e.rawScore,e.adjustScore)"
												+ " from ExamQualScoreDetail e right join e.examQualItemSet i where 1<>2");
								dynamicQuery
										.appendIfNotNull(
												"and i.organization.id =:organization_id",
												"organization_id", topOrgId);

								dynamicQuery.appendIfNotNull(
										"and e.examScore.id =:examscore_id",
										"examscore_id", examscoreId);
								return dynamicQuery.build(session);
							}
						}
					}, limit, sorter);
		} catch (Exception e) {
			throw new RuntimeException(
					"【异常原因：根据定性考核打分ID获取打分明细集合时数据库发生异常】【异常说明：+"
							+ e.getMessage()
							+ "】【发生地点：ExamQualScoreServiceImpl.searchExamQualScoreDetails;参数examscore_id="
							+ examscoreId + "】");
		}
	}

	@Override
	public LimitedList<ExamQualScore> searchExamQualScores(
			final ExamQualScore examQualScore,
			final ExamShowYearlyEnum examShowYearlyEnum, Limit limit,
			Sorter sorter) {
		if (examQualScore == null) {
			throw new RuntimeException(
					"【examQualScore参数异常】【发生地点：ExamQualScoreServiceImpl.searchExamQualScores】");
		}
		try {
			return dataAccessor.findByQuery(ExamQualScore.class,
					new QueryCreator() {
						@Override
						public Query createQuery(Session session) {
							// right join i.employeeinfoBase
							DynamicQuery dynamicQuery = new DynamicQuery(
									"from ExamQualScore e right join e.employeeinfoWork w where w.cancel <> 1");
							dynamicQuery
									.append("and w.employeeinfoWork.baseId.id = :employee_id",
											"employee_id", examQualScore
													.getEmployeeinfoWork()
													.getBaseId().getId());
							// 本年度
							if (examShowYearlyEnum == ExamShowYearlyEnum.present_year) {
								dynamicQuery
										.append(" YEAR(NOW())-YEAR(e.create_date) = 0");
							} else if (examShowYearlyEnum == ExamShowYearlyEnum.last_year) {
								dynamicQuery
										.append(" YEAR(NOW())-YEAR(e.create_date) = 1");
							}
							return dynamicQuery.build(session);
						}
					}, limit, sorter);
		} catch (Exception e) {
			throw new RuntimeException(
					"【异常原因：获取定性考核打分对象集合时数据库发生异常】【异常说明：+"
							+ e.getMessage()
							+ "】【发生地点：ExamQualScoreServiceImpl.searchExamQualScores;参数employee_id="
							+ examQualScore.getEmployeeinfoWork().getBaseId()
									.getId() + "】");
		}
	}

	@Override
	public void saveExamQualScore(ExamQualScore examQualScore) {
		if (examQualScore == null
				|| examQualScore.getEmployeeinfoWork() == null) {
			throw new RuntimeException("【examQualScore对象参数异常】");
		}
		try {
			dataAccessor.saveOrUpdate(examQualScore);
			
			if(examQualScore.getAdjustScore() != null && examQualScore.getAdjustScore() > 0){	//表示打特批分时，添加审核流程
				//添加审核
				List<List<ExamQualTargetAuditing>> audits = searchQualScoreTargetAuditings(examQualScore.getId(),
						null, null);
				if(audits == null || audits.size() <= 0){
					saveQualTargetAuditingProcess(examQualScore,1);
				}
			}
		} catch (Exception e) {
			throw new RuntimeException("【异常原因：保存定性考核打分对象到数据库发生异常】【异常说明："
					+ e.getMessage()
					+ "】【发生地点：ExamQualScoreServiceImpl.saveExamQualScore】");
		}
	}
	
	@Override
	public void saveQualTargetAuditingProcess(ExamQualScore examQualScore, int auditNo) {
		try {
			auditingRepository.saveAuditingProcess(examQualScore, auditNo);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	@Override
	public void saveExamQualScoreDetail(ExamQualScoreDetail examQualScoreDetail) {
		if (examQualScoreDetail == null
				|| examQualScoreDetail.getExamScore() == null) {
			throw new RuntimeException("【examQualScoreDetail对象参数异常】");
		}
		try {
			dataAccessor.saveOrUpdate(examQualScoreDetail);
		} catch (Exception e) {
			throw new RuntimeException(
					"【异常原因：保存定性考核打分明细对象到数据库发生异常】【异常说明："
							+ e.getMessage()
							+ "】【发生地点：ExamQualScoreServiceImpl.saveExamQualScoreDetail】");
		}
	}

	@Override
	public void removeExamQualScores(String examQualScoreIds) {
		// TODO Auto-generated method stub

	}

	@Override
	public void removeExamQualScoreDetails(String examQualScoreDetailIds) {
		// TODO Auto-generated method stub

	}

	
	@Override
	public List<List<ExamQualTargetAuditing>> searchQualScoreTargetAuditings(Long scoreId, Limit limit, Sorter sorter) {
		return auditingRepository.findByHql(ExamQualTargetAuditing.class, "from ExamQualTargetAuditing i where i.examQualScore.id = ?", new Object[] { scoreId });
	}
	
	@Override
	public Long analyseCountNOCurrentAuditing(final Long organizationId,final  String dutyIds,final  ExaminePeriodEnum periodType,
			final Long period,final  int status,final Long currentAuditerId) {
		try {
			String treepath = "";
			if (organizationId > 0) {
				try {
					treepath = dataAccessor.get(Organization.class,
							organizationId).getTreePath();
				} catch (Exception e) {
					return null;
				}
			}
			final String treePath = treepath;
			return dataAccessor.findUnique(Long.class, new QueryCreator() {

						@Override
						public Query createQuery(Session session) {
							Calendar mCalendar = Calendar.getInstance();
							mCalendar.add(Calendar.MONTH, -1);
							DynamicQuery dynamicQuery = new DynamicQuery(
									"select count(e.id) from ExamQualScore e right join e.employeeinfoWork w where w.cancel <> 1");

							// modify by henry #start ---->for the read all
							// child
							dynamicQuery
									.append("and w.organization.treePath like '"
											+ treePath + "%'");
							// modify by henry #end
							if (dutyIds != null && !dutyIds.isEmpty()) {
								dynamicQuery.append("and w.duty.id in("
										+ dutyIds + ")");
							}
							// 表示打过分的
							dynamicQuery.appendIfNotNull(
									"and e.examPeriod.periodType =:periodType",
									"periodType", periodType);
							dynamicQuery.append(
									"and e.examPeriod.id =:period_id",
									"period_id", period);
							if (status > 0) {
								dynamicQuery.append("and e.status =:status",
										"status", status);
							}
							dynamicQuery.append(" and e.currentAuditerId<>:currentAuditerId","currentAuditerId",currentAuditerId);
							dynamicQuery.append(" and e.currentAuditStatus<>:currentAuditStatus","currentAuditStatus",AuditStatus.reject_audit);
							dynamicQuery.append(" and e.adjustScore is not null");
							return dynamicQuery.build(session);
						}
					});
		} catch (Exception e) {
			throw new RuntimeException(
					"【异常原因：获取定性考核打分对象集合时数据库发生异常】【异常说明：+"
							+ e.getMessage()
							+ "】【发生地点：ExamQualScoreServiceImpl.analyseCountNOCurrentAuditing;参数organizationId="
							+ organizationId + ",periodType=" + periodType
							+ "】");
		}
	}
}
